package DataBaseManager;

import java.io.Serializable;
import java.util.ArrayList;

public class DataBase implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	ArrayList<Table> tables = new ArrayList<Table>();
	public ArrayList<Table> getListTables() {
		return tables;
	}
	
	public Table getTable(String tableName)
	{
		for (Table table : tables) {
			if(tableName.equals(table.getName()))
				return table;
		}
		return null;
	}
	
	private String name;

	public String getName() {
		return name;
	}
	
	public DataBase(String dbname){
		this.name = dbname;
	}
	
	public int getTableCount(){
		return this.getTableCount();
	}
	
	public void readDataBase(){
		
	}
	
	public void writeDataBase(){
		
	}
	
	public boolean tableIsExist(String nameTable){
		boolean isOK = false;
		int n = tables.size();
		for (int i = 0; i < n; i++) {
			if (nameTable.compareTo(tables.get(i).getName()) == 0) {
				isOK = true;
				break;
			}
		}
		return isOK;
	}
	
	public boolean addTable(Table newTable){
		boolean isOK = false;
		if(!tableIsExist(newTable.getName())){
			tables.add(newTable);
			isOK = true;
		}
		return isOK;
		
	}
	
	// kiem tra 2 mang field co bang nhau ko?
	public boolean checkPKInFields(ArrayList<Field> pK, ArrayList<Field> fields){
		boolean isOK = true;
		int nFK1 = pK.size();
		int nFK2 = fields.size();
		boolean isExist = false;
		
		for(int i=0; i<nFK1;i++){
			isExist = false;
			for(int j=0;j<nFK2;j++){
				if(pK.get(i).getName().compareTo(fields.get(j).getName())==0){
					isExist = true;
					break;
				}
			}
			if(isExist == false){
				isOK = false;
			}
		}
		return isOK;
	}
	// kiem tra co bang khoa chinh cua bang co la khoa ngoai cua nhung bang khac ko?
	/*public boolean checkReferenceForeign(Table table){
		boolean isOK = false;
		int n = tables.size();
		
		for(int i =0;i<n;i++){
			if(table.getName().compareTo(tables.get(i).getName())!=0){
				if(checkPKInFields(table.getPK(), tables.get(i).getFields())){
					isOK = true;
					break;
				}
			}
		}
		
		return isOK;
	}*/
	
	public boolean deleteTable(Table table){
		boolean isOK = true;
		//if(tableIsExist(table.getName())){
			// neu bang ton tai trong database
			/*if(!checkReferenceForeign(table)) {
				// khoa chinh cua bang ko thuoc foreign key o bang khac
				tables.remove(table);
			}*/
		//}
		this.tables.remove(table);
		return isOK;
	}

	

}
